package com.beiming.libra.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import com.beiming.libra.common.AppException;
import com.beiming.libra.common.Assert;
import com.beiming.libra.common.constants.ValidateMessage;
import com.beiming.libra.common.enums.ErrorCode;
import com.beiming.libra.common.enums.StatusEnum;
import com.beiming.libra.common.page.Page;
import com.beiming.libra.common.page.PageResult;
import com.beiming.libra.dao.AuthRoleRelationMapper;
import com.beiming.libra.dao.MenuInfoMapper;
import com.beiming.libra.domain.AuthRoleRelation;
import com.beiming.libra.domain.MenuInfo;
import com.beiming.libra.domain.dto.MenuChildTreeDTO;
import com.beiming.libra.domain.dto.MenuTreeDTO;
import com.beiming.libra.domain.dto.requestdto.MenuInfoRequestDTO;
import com.beiming.libra.service.MenuInfoService;


/***
 * 
 * @author weibo
 * */
@Service
@Slf4j
public class MenuInfoServiceImpl implements MenuInfoService {
  @Resource
  private MenuInfoMapper menuInfoMapper;
  @Resource
  private AuthRoleRelationMapper authRoleRelationMapper;

  /**
   * 新增菜单
   */
  @Override
  public void insertMenuInfo(MenuInfoRequestDTO menuInfoRequestDTO) {
    MenuInfo menu = new MenuInfo();
    Assert.isNotEmpty(menuInfoRequestDTO.getMenuName(), ErrorCode.ILLEGAL_PARAMETER,
        ValidateMessage.NAME_NOT_BLANK);
    menu.setMenuName(menuInfoRequestDTO.getMenuName());
    if (menuInfoRequestDTO.getParentId() == null) {
      // 默认。。父级为0
      menuInfoRequestDTO.setParentId(0l);
    }
    // 新增菜单，同一个父级菜单，只能存在同一个名称
    Example example = new Example(MenuInfo.class, false);
    example.createCriteria().andEqualTo("menuName", menuInfoRequestDTO.getMenuName())
        .andEqualTo("parentId", menuInfoRequestDTO.getParentId());
    MenuInfo existMenu = menuInfoMapper.selectOneByExample(example);
    Assert.isNull(existMenu, ErrorCode.ILLEGAL_PARAMETER, ValidateMessage.NAME_EXISTS);
    menu.setMenuFlag(menuInfoRequestDTO.getMenuFlag());
    menu.setMenuType(menuInfoRequestDTO.getMenuType());
    menu.setMenuUrl(menuInfoRequestDTO.getMenuUrl());
    menu.setMenuOrderNo(menuInfoRequestDTO.getMenuOrderNo());

    menu.setStatus(StatusEnum.USED.getCode());
    menu.setRemark(menuInfoRequestDTO.getRemark());
    menu.setCreateTime(new Date());
    menu.setCreateUser(menuInfoRequestDTO.getCreateUser());
    menu.setVersion(0);
    menuInfoMapper.insert(menu);
  }

  /**
   * 获取菜单信息
   */
  @Override
  public MenuInfo getMenuInfo(String menuId) {
    Assert.isNotNull(menuId, ErrorCode.ILLEGAL_PARAMETER, ValidateMessage.ID_NOT_BLANK);
    return menuInfoMapper.selectByPrimaryKey(menuId);
  }


  /**
   * 获取菜单列表
   */
  @Override
  public PageResult<MenuInfo> listMenuInfo(MenuInfoRequestDTO menuInfoRequestDTO) {
    List<MenuInfo> list =
        menuInfoMapper.listMenuInfo(menuInfoRequestDTO.getMenuName(),
            (menuInfoRequestDTO.getPageNo() - 1) * menuInfoRequestDTO.getPageSize(),
            menuInfoRequestDTO.getPageSize());
    PageResult<MenuInfo> pageResult = new PageResult<MenuInfo>();
    pageResult.setList(list);
    int total = menuInfoMapper.listMenuInfoCount(menuInfoRequestDTO.getMenuName());
    Page page = new Page();

    page.setPageNo(menuInfoRequestDTO.getPageNo());
    page.setPageSize(menuInfoRequestDTO.getPageSize());
    page.setTotalRecords(total);
    pageResult.setPage(page);
    return pageResult;
  }

  /** 更新菜单 */
  @Override
  public void updateMeunInfo(MenuInfoRequestDTO menuInfoRequestDTO) {
    Long menuId = menuInfoRequestDTO.getId();
    Assert.isNotNull(menuId, ErrorCode.ILLEGAL_PARAMETER, ValidateMessage.ID_NOT_BLANK);
    MenuInfo menu = menuInfoMapper.selectByPrimaryKey(menuId);
    Assert.isNotNull(menu, ErrorCode.ILLEGAL_PARAMETER, ValidateMessage.ID_NOT_EXISTS);
    // 菜单名称和菜单父级必填
    menu.setParentId(menuInfoRequestDTO.getParentId());
    menu.setMenuName(menuInfoRequestDTO.getMenuName());
    Example example = new Example(MenuInfo.class, false);
    example.createCriteria().andEqualTo("menuName", menuInfoRequestDTO.getMenuName())
        .andEqualTo("parentId", menuInfoRequestDTO.getParentId());
    MenuInfo existMenuInfo = menuInfoMapper.selectOneByExample(example);
    if (existMenuInfo.getId().equals(menuId)) {
      throw new AppException(ErrorCode.ILLEGAL_PARAMETER, ValidateMessage.NAME_EXISTS);
    }
    if (!StringUtils.isEmpty(menuInfoRequestDTO.getMenuFlag())) {
      menu.setMenuFlag(menuInfoRequestDTO.getMenuFlag());
    }
    if (!StringUtils.isEmpty(menuInfoRequestDTO.getMenuUrl())) {
      menu.setMenuUrl(menuInfoRequestDTO.getMenuUrl());
    }
    if (menuInfoRequestDTO.getMenuOrderNo() != null) {
      menu.setMenuOrderNo(menuInfoRequestDTO.getMenuOrderNo());
    }
    menu.setUpdateTime(new Date());
    menu.setUpdateUser(menuInfoRequestDTO.getUpdateUser());
    menuInfoMapper.updateByPrimaryKey(menu);
  }

  /**
   * 获取树形菜单数据
   * */
  @Override
  public MenuTreeDTO getMenusTree() {
    MenuTreeDTO tree = new MenuTreeDTO("0", "菜单", "open", null);
    // 获取最父级节点
    List<MenuInfo> menuTop = menuInfoMapper.selectByParentId("01");
    if (menuTop != null && menuTop.size() > 0) {
      List<MenuChildTreeDTO> child = new ArrayList<MenuChildTreeDTO>();
      for (MenuInfo item : menuTop) {
        MenuChildTreeDTO ctree = initTree(item, menuTop);
        child.add(ctree);
      }
      tree.setChildren(child);
    }
    return tree;
  }

  /***
   * 子节点获取 递归获取
   * */
  public MenuChildTreeDTO initTree(MenuInfo item, List<MenuInfo> menus) {
    if (item == null) {
      return null;
    }
    MenuChildTreeDTO ct = new MenuChildTreeDTO();
    ct.setId(item.getId() + "");
    ct.setText(item.getMenuName());
    ct.setChildren(new ArrayList<MenuChildTreeDTO>());

    List<MenuInfo> thirdMenus = menuInfoMapper.selectByParentId(item.getId());
    if (thirdMenus != null && thirdMenus.size() > 0) {
      List<MenuChildTreeDTO> forrth = new ArrayList<MenuChildTreeDTO>();
      for (MenuInfo third : thirdMenus) {
        MenuChildTreeDTO ctree = initTree(third, menus);
        forrth.add(ctree);
      }
      ct.setChildren(forrth);
    }
    return ct;
  }

  @Override
  public void deleteMenuInfo(String menuId) {
    Assert.isNotNull(menuId, ErrorCode.ILLEGAL_PARAMETER, ValidateMessage.ID_NOT_BLANK);
    Example example = new Example(AuthRoleRelation.class, false);
    example.createCriteria().andEqualTo("menuId", menuId);
    int count = authRoleRelationMapper.selectCountByExample(example);
    if (count > 0) {
      throw new AppException(ErrorCode.ILLEGAL_PARAMETER, ValidateMessage.MENU_BEING_USED);
    }
    MenuInfo menu = menuInfoMapper.selectByPrimaryKey(menuId);
    Assert.isNotNull(menu, ErrorCode.ILLEGAL_PARAMETER, ValidateMessage.ID_NOT_EXISTS);
    menuInfoMapper.delete(menu);
  }
}
